<template>
  <div class="font-sans">
    <!-- 初始加载动画 -->
    <InitialLoader />
    <div class="min-h-screen bg-gradient-to-br from-slate-50 via-blue-50 to-indigo-100 text-slate-800 relative overflow-hidden">
      <!-- 背景装饰 -->
      <div class="absolute bottom-0 left-0 w-full pointer-events-none">
        <img src="/wave-bg.svg" alt="" class="w-full" />
      </div>
      <div class="absolute top-0 right-0 w-full h-full pointer-events-none bg-repeat opacity-30" style="background-image: url('/dots-pattern.svg')">
      </div>
      
      <div class="flex h-screen overflow-hidden">
        <!-- 侧边栏导航 -->
        <div class="admin-sidebar w-64 h-full bg-white/90 backdrop-blur-sm shadow-2xl border-r border-white/20 z-20 transition-all duration-300 relative">
                      <div class="p-6 border-b border-slate-200/50 bg-gradient-to-r from-white/80 to-slate-50/80">
                          <NuxtLink to="/" class="text-xl font-bold text-transparent bg-clip-text bg-gradient-to-r from-indigo-600 via-purple-600 to-blue-600 hover:from-indigo-500 hover:via-purple-500 hover:to-blue-500 no-underline transition-all duration-300 flex items-center">
              <span class="mr-2">新闻聚合平台</span>
            </NuxtLink>
          </div>
          
          <div class="py-4 px-2">
            <el-menu 
              class="admin-menu border-none" 
              :default-active="activeMenu"
              @select="handleMenuSelect"
              :router="true"
              :unique-opened="true"
            >
              <el-menu-item index="/admin/dashboard" class="menu-item-custom">
                <el-icon><i class="el-icon-menu"></i></el-icon>
                <span>控制面板</span>
              </el-menu-item>
              
              <el-sub-menu index="news" class="submenu-custom">
                <template #title>
                  <el-icon><i class="el-icon-document"></i></el-icon>
                  <span>新闻管理</span>
                </template>
                <el-menu-item index="/admin/news/list" class="submenu-item-custom">新闻列表</el-menu-item>
                <el-menu-item index="/admin/news/add" class="submenu-item-custom">添加新闻</el-menu-item>
              </el-sub-menu>
              
              <el-sub-menu index="source" class="submenu-custom">
                <template #title>
                  <el-icon><i class="el-icon-connection"></i></el-icon>
                  <span>信源管理</span>
                </template>
                <el-menu-item index="/admin/source/list" class="submenu-item-custom">信源列表</el-menu-item>
                <el-menu-item index="/admin/source/add" class="submenu-item-custom">添加信源</el-menu-item>
              </el-sub-menu>
              
              <el-sub-menu index="category" class="submenu-custom">
                <template #title>
                  <el-icon><i class="el-icon-collection-tag"></i></el-icon>
                  <span>分类管理</span>
                </template>
                <el-menu-item index="/admin/category/list" class="submenu-item-custom">分类列表</el-menu-item>
                <el-menu-item index="/admin/category/add" class="submenu-item-custom">添加分类</el-menu-item>
              </el-sub-menu>
              
              <el-sub-menu index="region" class="submenu-custom">
                <template #title>
                  <el-icon><i class="el-icon-location"></i></el-icon>
                  <span>区域管理</span>
                </template>
                <el-menu-item index="/admin/region/list" class="submenu-item-custom">区域列表</el-menu-item>
                <el-menu-item index="/admin/region/add" class="submenu-item-custom">添加区域</el-menu-item>
              </el-sub-menu>
              
              <el-sub-menu index="fetch" class="submenu-custom">
                <template #title>
                  <el-icon><i class="el-icon-link"></i></el-icon>
                  <span>抓取中心</span>
                </template>
                <el-menu-item index="/admin/fetch/tasks" class="submenu-item-custom">任务视图</el-menu-item>
                <el-menu-item index="/admin/fetch/rss/list" class="submenu-item-custom">RSS 源</el-menu-item>
                <el-menu-item index="/admin/fetch/api/list" class="submenu-item-custom">API 源</el-menu-item>
                <el-menu-item index="/admin/fetch/logs" class="submenu-item-custom">抓取日志</el-menu-item>
              </el-sub-menu>

              
              
              <el-sub-menu index="system" class="submenu-custom">
                <template #title>
                  <el-icon><i class="el-icon-setting"></i></el-icon>
                  <span>系统设置</span>
                </template>
                <el-menu-item index="/admin/system/settings" class="submenu-item-custom">基本设置</el-menu-item>
                <el-menu-item index="/admin/system/api" class="submenu-item-custom">API配置</el-menu-item>
              </el-sub-menu>
              
              <el-sub-menu index="user" class="submenu-custom">
                <template #title>
                  <el-icon><i class="el-icon-user"></i></el-icon>
                  <span>用户管理</span>
                </template>
                <el-menu-item index="/admin/user/list" class="submenu-item-custom">用户列表</el-menu-item>
                <el-menu-item index="/admin/user/add" class="submenu-item-custom">添加用户</el-menu-item>
                <el-menu-item index="/admin/user/roles" class="submenu-item-custom">角色权限</el-menu-item>
              </el-sub-menu>
              
              <el-sub-menu index="stats" class="submenu-custom">
                <template #title>
                  <el-icon><i class="el-icon-data-analysis"></i></el-icon>
                  <span>数据统计</span>
                </template>
                <el-menu-item index="/admin/stats/overview" class="submenu-item-custom">数据概览</el-menu-item>
                <el-menu-item index="/admin/stats/news" class="submenu-item-custom">新闻统计</el-menu-item>
                <el-menu-item index="/admin/stats/system" class="submenu-item-custom">系统性能</el-menu-item>
              </el-sub-menu>
              
              <el-sub-menu index="monitor" class="submenu-custom">
                <template #title>
                  <el-icon><i class="el-icon-monitor"></i></el-icon>
                  <span>系统监控</span>
                </template>
                <el-menu-item index="/admin/monitor/overview" class="submenu-item-custom">监控概览</el-menu-item>
                <el-menu-item index="/admin/monitor/logs" class="submenu-item-custom">日志中心</el-menu-item>
                <el-menu-item index="/admin/monitor/performance" class="submenu-item-custom">性能分析</el-menu-item>
              </el-sub-menu>
            </el-menu>
          </div>
        </div>
        
        <!-- 主内容区域 -->
        <div class="flex-1 flex flex-col overflow-hidden">
          <!-- 顶部导航栏 -->
          <header class="bg-white/80 backdrop-blur-sm shadow-lg border-b border-white/20 h-16 flex items-center justify-between px-6 z-10">
            <div class="flex items-center">
              <el-breadcrumb separator="/" class="hidden sm:flex">
                <el-breadcrumb-item :to="{ path: '/admin/dashboard' }">管理后台</el-breadcrumb-item>
                <el-breadcrumb-item v-for="(item, index) in breadcrumbs" :key="index" :to="item.path">
                  {{ item.title }}
                </el-breadcrumb-item>
              </el-breadcrumb>
            </div>
            
            <div class="flex items-center space-x-4">
              <el-dropdown trigger="click">
                <span class="flex items-center cursor-pointer hover:bg-slate-100 px-3 py-2 rounded-lg transition-all duration-200">
                                      <span class="hidden sm:inline-block mr-2 text-slate-600 font-medium">{{ userInfo.name || '管理员' }}</span>
                                      <el-avatar :size="32" :src="userInfo.avatar || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'" class="ring-2 ring-white/20" />
                </span>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item @click="navigateTo('/admin/user/profile')">个人信息</el-dropdown-item>
                    <el-dropdown-item @click="logout">退出登录</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </header>
          
          <!-- 页面内容 -->
          <main class="flex-1 overflow-auto p-6 relative">
            <!-- 装饰元素 -->
            <div class="absolute top-20 left-10 w-32 h-32 rounded-full bg-gradient-to-r from-indigo-500/10 to-purple-500/10 blur-3xl pointer-events-none animate-pulse"></div>
            <div class="absolute bottom-20 right-10 w-40 h-40 rounded-full bg-gradient-to-r from-blue-500/10 to-indigo-500/10 blur-3xl pointer-events-none animate-pulse"></div>
            
            <!-- 装饰性图标 -->
            <div class="absolute top-10 right-20 opacity-30 pointer-events-none animate-bounce">
              <DecorativeIcon type="star" />
            </div>
            <div class="absolute bottom-10 left-20 opacity-30 pointer-events-none animate-bounce" style="animation-delay: 1s;">
              <DecorativeIcon type="lightning" />
            </div>
            
            <PageTransition>
              <slot />
            </PageTransition>
          </main>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useAuth } from '~/composables/useAuth'
import InitialLoader from '~/components/InitialLoader.vue'
import DecorativeIcon from '~/components/DecorativeIcon.vue'
import PageTransition from '~/components/PageTransition.vue'

// 使用认证管理
const { currentUser, isLoggedIn, logout: authLogout, checkAuthValidity } = useAuth()




// 用户信息
const userInfo = computed(() => {
  if (currentUser.value) {
    return {
      id: currentUser.value.id,
      username: currentUser.value.username,
      role: currentUser.value.role,
      name: currentUser.value.name || currentUser.value.username,
      avatar: currentUser.value.avatar || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'
    }
  }
  return {
    id: null,
    username: '',
    role: '',
    name: '管理员',
    avatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'
  }
})

// 检查系统偏好和获取用户信息
onMounted(() => {

  
  // 检查登录状态
  const isValid = checkAuthValidity()
  if (!isValid && route.path !== '/admin/login') {
    // 未登录，跳转到登录页面
    router.push('/admin/login')
  }
})

// 路由
const route = useRoute()
const router = useRouter()

// 面包屑导航
const breadcrumbs = computed(() => {
  const path = route.path
  const pathSegments = path.split('/').filter(Boolean)
  
  // 移除 'admin' 前缀，因为已经在固定的第一个面包屑中
  if (pathSegments[0] === 'admin') {
    pathSegments.shift()
  }
  
  // 构建面包屑数组
  const result = []
  let currentPath = '/admin'
  
  for (let i = 0; i < pathSegments.length; i++) {
    currentPath += `/${pathSegments[i]}`
    
    // 将路径片段转换为更友好的标题
    let title = pathSegments[i].charAt(0).toUpperCase() + pathSegments[i].slice(1)
    
    // 特殊情况处理
    if (title === 'Dashboard') title = '控制面板'
    if (title === 'News') title = '新闻管理'
    if (title === 'Source') title = '信源管理'
    if (title === 'Category') title = '分类管理'
    if (title === 'Region') title = '区域管理'
    if (title === 'Task') title = '抓取任务管理'
    if (title === 'Fetch') title = '抓取中心'
    if (title === 'Tasks') title = '任务视图'
    if (title === 'Rss') title = 'RSS 源'
    if (title === 'System') title = '系统设置'
    if (title === 'User') title = '用户管理'
    if (title === 'Stats') title = '数据统计'
    if (title === 'List') title = '列表'
    if (title === 'Add') title = '添加'
    if (title === 'Edit') title = '编辑'
    if (title === 'Settings') title = '设置'
    if (title === 'Logs') title = '日志'
    if (title === 'Roles') title = '角色权限'
    if (title === 'Profile') title = '个人信息'
    if (title === 'Overview') title = '数据概览'
    // API 面包屑：在系统设置下显示“API配置”，在抓取中心下显示“API 源”
    if (title === 'Api') {
      if (i > 0 && pathSegments[i - 1] === 'fetch') {
        title = 'API 源'
      } else {
        title = 'API配置'
      }
    }
    
    result.push({
      path: currentPath,
      title: title
    })
  }
  
  return result
})

// 当前活动菜单
const activeMenu = computed(() => {
  return route.path
})

// 菜单选择处理
const handleMenuSelect = (index) => {
  router.push(index)
}

// 退出登录
const logout = async () => {
  console.log('🚪 开始退出登录...')
  
  try {
    // 使用认证管理的退出登录方法
    console.log('📞 调用认证管理退出登录...')
    await authLogout()
    console.log('✅ 认证管理退出登录完成')
    
    // 显示退出成功消息
    ElMessage({
      message: '已退出登录',
      type: 'success',
      duration: 1000
    })
    
    // 强制刷新页面，确保状态完全清除
    console.log('🔄 准备强制刷新页面...')
    
    // 先清除所有状态
    localStorage.clear()
    sessionStorage.clear()
    
    // 等待消息显示完成后再跳转
    setTimeout(() => {
      console.log('🚀 执行强制跳转...')
      window.location.href = '/admin/login'
    }, 1000)
    
  } catch (error) {
    console.error('❌ 退出登录失败:', error)
    ElMessage({
      message: '退出登录失败',
      type: 'error',
      duration: 1000
    })
    
    // 即使失败也要强制刷新
    setTimeout(() => {
      localStorage.clear()
      sessionStorage.clear()
      window.location.href = '/admin/login'
    }, 1000)
  }
}

// 页面导航
const navigateTo = (path) => {
  router.push(path)
}
</script>

<style scoped>
.admin-sidebar {
  transition: all 0.2s ease;
}

.admin-menu {
  border-right: none !important;
  background-color: transparent !important;
}

:deep(.el-menu) {
  border-right: none !important;
  background-color: transparent !important;
}

/* 主菜单项样式 */
:deep(.menu-item-custom) {
  height: 50px;
  line-height: 50px;
  color: var(--light-text);
  transition: all 0.15s ease;
  margin: 4px 8px;
  border-radius: 12px;
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.1), rgba(255, 255, 255, 0.05));
  border: 1px solid rgba(255, 255, 255, 0.1);
}



/* 子菜单样式 */
:deep(.submenu-custom .el-sub-menu__title) {
  height: 50px;
  line-height: 50px;
  color: var(--light-text);
  transition: all 0.05s ease;
  margin: 4px 8px;
  border-radius: 12px;
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.1), rgba(255, 255, 255, 0.05));
  border: 1px solid rgba(255, 255, 255, 0.1);
}



/* 子菜单项样式 */
:deep(.submenu-item-custom) {
  height: 45px;
  line-height: 45px;
  color: var(--light-text);
  transition: all 0.1s ease;
  margin: 2px 16px;
  border-radius: 10px;
  /* 子菜单：颜色稍加深，便于与父级区分 */
  background: linear-gradient(135deg, rgba(79, 70, 229, 0.045), rgba(99, 102, 241, 0.03));
  border: 1px solid rgba(255, 255, 255, 0.05);
}



/* 激活状态样式 */
:deep(.menu-item-custom.is-active) {
  color: var(--primary-color) !important;
  background: linear-gradient(135deg, rgba(79, 70, 229, 0.2), rgba(99, 102, 241, 0.15)) !important;
  box-shadow: 0 4px 15px rgba(79, 70, 229, 0.3);
  transform: translateY(-1px);
}



:deep(.submenu-item-custom.is-active) {
  color: var(--primary-color) !important;
  background: linear-gradient(135deg, rgba(79, 70, 229, 0.15), rgba(99, 102, 241, 0.1)) !important;
  box-shadow: 0 2px 10px rgba(79, 70, 229, 0.2);
}



/* 悬停效果 */
:deep(.menu-item-custom:hover),
:deep(.submenu-custom .el-sub-menu__title:hover) {
  background: linear-gradient(135deg, rgba(79, 70, 229, 0.1), rgba(99, 102, 241, 0.05)) !important;
  transform: translateY(-1px);
  box-shadow: 0 2px 10px rgba(79, 70, 229, 0.2);
  transition: all 0.15s ease;
}



:deep(.submenu-item-custom:hover) {
  background: linear-gradient(135deg, rgba(79, 70, 229, 0.08), rgba(99, 102, 241, 0.03)) !important;
  transform: translateX(2px);
  transition: all 0.1s ease;
}



:deep(.sub-menu.is-active .el-sub-menu__title) {
  color: var(--primary-color) !important;
}


</style>